//
// Copyright (C) 2011 - 2013  Steve Channell steve.channell@cepheis.com
//
// This file is part of Cephei.QL, an open-source library wrapper 
// arround QuantLib http://quantlib.org/
//
// Cephei.QL is open source software: you can redistribute it and/or modify it
// under the terms of the license.  You should have received a
// copy of the license along with this program; if not, please email
// <support@cepheis.com>. The license is also available online at
// <http://cepheis.com/license.htm>.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
// FOR A PARTICULAR PURPOSE.  See the license for more details.
//
// Version 2.2 with QuantLib 1.2.1
//#include "stdafx.h"
#include "CalibratedModel.h"
using namespace Cephei::QL::Models;
#include <gen/QL/Models/CalibrationHelper.h>
#include <gen/QL/Math/Optimization/OptimizationMethod.h>
#include <gen/QL/Math/Optimization/EndCriteria.h>
#include <gen/QL/Math/Optimization/Constraint.h>
#include <gen/QL/Math/Array.h>
using namespace Cephei::QL::Math::Optimization;
using namespace Cephei::QL::Math;
#define HANDLE
#undef ABSTRACT
#undef STRUCT
Cephei::QL::Models::CCalibratedModel::CCalibratedModel (UInt64 nArguments) 
{
	_pSpinlock = new boost::detail::spinlock ();
    try
    {
#ifdef HANDLE
        _phCalibratedModel = NULL;
#endif
        QuantLib::Size _nArguments = (QuantLib::Size)ValueHelper::Convert (nArguments); //d
        _ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (new QuantLib::CalibratedModel ( _nArguments ));
        
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Cephei::QL::Models::CCalibratedModel::CCalibratedModel (boost::shared_ptr<QuantLib::CalibratedModel>& childNative, Object^ owner) 
{
	_pSpinlock = new boost::detail::spinlock ();
#ifdef HANDLE
	_phCalibratedModel = NULL;
#endif
	_ppCalibratedModel = &childNative;
    
}
Cephei::QL::Models::CCalibratedModel::CCalibratedModel (QuantLib::CalibratedModel& childNative, Object^ owner) 
{
#ifdef HANDLE
	_phCalibratedModel = NULL;
#endif
	_ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (&childNative);
    
    _CalibratedModelOwner = owner;
    
}

Cephei::QL::Models::CCalibratedModel::CCalibratedModel (CCalibratedModel^ copy) 
{
	_pSpinlock = new boost::detail::spinlock ();
#ifdef HANDLE
	_phCalibratedModel = NULL;
#endif
	if (copy->HasNative() != NULL)
    {
		_ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (copy->GetShared());
        
    }
}
Cephei::QL::Models::CCalibratedModel::CCalibratedModel (PLATFORM::Type^ t) 
{
	_pSpinlock = new boost::detail::spinlock ();
#ifdef HANDLE
	_phCalibratedModel = NULL;
#endif
	if (!t->IsSubclassOf(CCalibratedModel::typeid))
		throw REFNEW Exception ("Invalid base-case init");
}
#ifdef HANDLE
Cephei::QL::Models::CCalibratedModel::CCalibratedModel (QuantLib::Handle<QuantLib::CalibratedModel>& childNative, Object^ owner)  
{
	_pSpinlock = new boost::detail::spinlock ();
	_phCalibratedModel = &childNative;
	_ppCalibratedModel = &static_cast<boost::shared_ptr<QuantLib::CalibratedModel>>(childNative.currentLink());
    
    _CalibratedModelOwner = owner;
}
Cephei::QL::Models::CCalibratedModel::CCalibratedModel (QuantLib::Handle<QuantLib::CalibratedModel> childNative)  
{
	_pSpinlock = new boost::detail::spinlock ();
	_phCalibratedModel = &childNative;
	_ppCalibratedModel = &static_cast<boost::shared_ptr<QuantLib::CalibratedModel>>(childNative.currentLink());
    
}
#endif
#ifdef STRUCT
Cephei::QL::Models::CCalibratedModel::CCalibratedModel (QuantLib::CalibratedModel childNative)  
{
	_pSpinlock = new boost::detail::spinlock ();
#ifdef HANDLE
	_phCalibratedModel = NULL;
#endif
	_ppCalibratedModel = new boost::shared_ptr<QuantLib::CalibratedModel> (new QuantLib::CalibratedModel (childNative));
    
}
#endif

Cephei::QL::Models::CCalibratedModel::~CCalibratedModel ()
{
	if (_pSpinlock != NULL)
    {
        delete _pSpinlock;
        _pSpinlock = NULL;
    }
    if (_ppCalibratedModel != NULL)
    {
	    delete _ppCalibratedModel;
        _ppCalibratedModel = NULL;
    }
}
Cephei::QL::Models::CCalibratedModel::!CCalibratedModel ()
{
	if (_pSpinlock != NULL)
    {
        delete _pSpinlock;
    }
    if (_ppCalibratedModel != NULL)
    {
	    delete _ppCalibratedModel;
    }
}
QuantLib::CalibratedModel& Cephei::QL::Models::CCalibratedModel::GetReference ()
{
    if (_ppCalibratedModel == NULL) throw REFNEW NativeNullException ();
	return **_ppCalibratedModel;
}
boost::shared_ptr<QuantLib::CalibratedModel>& Cephei::QL::Models::CCalibratedModel::GetShared ()
{
    if (_ppCalibratedModel == NULL) throw REFNEW NativeNullException ();
	return *_ppCalibratedModel;
}
QuantLib::CalibratedModel* Cephei::QL::Models::CCalibratedModel::GetPointer ()
{
    if (_ppCalibratedModel == NULL) throw REFNEW NativeNullException ();
	return &**_ppCalibratedModel;
}
#ifdef HANDLE
QuantLib::Handle<QuantLib::CalibratedModel>& Cephei::QL::Models::CCalibratedModel::GetHandle ()
{
	if (_phCalibratedModel == NULL)
	{
		_phCalibratedModel = new Handle<QuantLib::CalibratedModel> (*_ppCalibratedModel);
	}
	return *_phCalibratedModel;
}
#endif
bool Cephei::QL::Models::CCalibratedModel::HasNative () 
{
	return (_ppCalibratedModel != NULL);
}

Cephei::QL::Models::ICalibratedModel^ Cephei::QL::Models::CCalibratedModel::Calibrate (Cephei::Core::IVector<Cephei::QL::Models::ICalibrationHelper^>^ instruments, Cephei::QL::Math::Optimization::IOptimizationMethod^ method, Cephei::QL::Math::Optimization::IEndCriteria^ endCriteria, Microsoft::FSharp::Core::FSharpOption<Cephei::QL::Math::Optimization::IConstraint^>^ constraint, Microsoft::FSharp::Core::FSharpOption<Cephei::Core::IVector<Double>^>^ weights)
{
    COptimizationMethod^ _Cmethod;
    CEndCriteria^ _CendCriteria;
    CConstraint^ _Cconstraint;
    try
    {
    	boost::detail::spinlock::scoped_lock lock (*_pSpinlock);
        instruments->Lock();
        INativeVector<Cephei::QL::Models::ICalibrationHelper^>^ _NCIinstruments = instruments->getFeature (NativeFeature::shared_ptr);
        CCalibrationHelperVector^ _NCinstruments = safe_cast<CCalibrationHelperVector^>(_NCIinstruments);
        std::vector<boost::shared_ptr<QuantLib::CalibrationHelper> >& _instruments = static_cast<std::vector<boost::shared_ptr<QuantLib::CalibrationHelper> >&> (_NCinstruments->GetShared ());
        _Cmethod = safe_cast<COptimizationMethod^> (method);
        _Cmethod->Lock();
        QuantLib::OptimizationMethod& _method = static_cast<QuantLib::OptimizationMethod&> (_Cmethod->GetReference ()); 
        _CendCriteria = safe_cast<CEndCriteria^> (endCriteria);
        _CendCriteria->Lock();
        QuantLib::EndCriteria& _endCriteria = static_cast<QuantLib::EndCriteria&> (_CendCriteria->GetReference ()); 
        if (Microsoft::FSharp::Core::FSharpOption<Cephei::QL::Math::Optimization::IConstraint^>::IsSome::get (constraint))
        {
            _Cconstraint = safe_cast<CConstraint^> (constraint->Value);
            _Cconstraint->Lock();
        }
        QuantLib::Constraint& _constraint = 
            (Microsoft::FSharp::Core::FSharpOption<Cephei::QL::Math::Optimization::IConstraint^>::IsSome::get (constraint) ? static_cast<QuantLib::Constraint&> (_Cconstraint->GetReference ()) : QuantLib::Constraint()); //6
        CDoubleVector^ _NCweights;
        if (Microsoft::FSharp::Core::FSharpOption<Cephei::Core::IVector<Double>^>::IsSome::get (weights))
        {
            weights->Value->Lock();
            INativeVector<Double>^ _NCIweights = weights->Value->getFeature (NativeFeature::Value);
            _NCweights = safe_cast<CDoubleVector^>(_NCIweights);
        }
        std::vector<QuantLib::Real>& _weights = 
            (Microsoft::FSharp::Core::FSharpOption<Cephei::Core::IVector<Double>^>::IsSome::get (weights) ? static_cast<std::vector<QuantLib::Real>&> (_NCweights->GetReference ()) : std::vector<QuantLib::Real>()); //8
    	(*_ppCalibratedModel)->calibrate ( _instruments,  _method,  _endCriteria,  _constraint,  _weights );
    	return this;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
        if (instruments != nullptr) instruments->Unlock(); //NO2  
        if (_Cmethod != nullptr) _Cmethod->Unlock();
        if (_CendCriteria != nullptr) _CendCriteria->Unlock();
        if (_Cconstraint != nullptr) _Cconstraint->Unlock();
        if (weights != nullptr) weights->Value->Unlock();
    }
}
Cephei::QL::Math::Optimization::IConstraint^ Cephei::QL::Models::CCalibratedModel::Constraint::get ()
{
    try
    {
    	boost::shared_ptr<QuantLib::Constraint>& _rv = (boost::shared_ptr<QuantLib::Constraint>&)(*_ppCalibratedModel)->constraint ( );   
        Cephei::QL::Math::Optimization::CConstraint^ _nrv = REFNEW Cephei::QL::Math::Optimization::CConstraint (_rv, this);
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
QL::Math::Optimization::EndCriteria::TypeEnum Cephei::QL::Models::CCalibratedModel::EndCriteria::get ()
{
    try
    {
    	boost::detail::spinlock::scoped_lock lock (*_pSpinlock);
    	QuantLib::EndCriteria::Type _rv = (QuantLib::EndCriteria::Type)(*_ppCalibratedModel)->endCriteria ( );   
        QL::Math::Optimization::EndCriteria::TypeEnum _nrv = (QL::Math::Optimization::EndCriteria::TypeEnum)_rv;
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Cephei::QL::Models::ICalibratedModel^ Cephei::QL::Models::CCalibratedModel::SetParams (Cephei::QL::Math::IArray^ p_params)
{
    CArray^ _Cp_params;
    try
    {
    	boost::detail::spinlock::scoped_lock lock (*_pSpinlock);
        _Cp_params = safe_cast<CArray^> (p_params);
        _Cp_params->Lock();
        QuantLib::Array& _p_params = static_cast<QuantLib::Array&> (_Cp_params->GetReference ()); 
    	(*_ppCalibratedModel)->setParams ( _p_params );
    	return this;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
        if (_Cp_params != nullptr) _Cp_params->Unlock();
    }
}
Cephei::QL::Models::ICalibratedModel^ Cephei::QL::Models::CCalibratedModel::Update::get ()
{
    try
    {
    	boost::detail::spinlock::scoped_lock lock (*_pSpinlock);
    	(*_ppCalibratedModel)->update ( );
    	return this;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
    }
}
Double Cephei::QL::Models::CCalibratedModel::Value (Cephei::QL::Math::IArray^ p_params, Cephei::Core::IVector<Cephei::QL::Models::ICalibrationHelper^>^ instruments)
{
    CArray^ _Cp_params;
    try
    {
    	boost::detail::spinlock::scoped_lock lock (*_pSpinlock);
        _Cp_params = safe_cast<CArray^> (p_params);
        _Cp_params->Lock();
        QuantLib::Array& _p_params = static_cast<QuantLib::Array&> (_Cp_params->GetReference ()); 
        instruments->Lock();
        INativeVector<Cephei::QL::Models::ICalibrationHelper^>^ _NCIinstruments = instruments->getFeature (NativeFeature::shared_ptr);
        CCalibrationHelperVector^ _NCinstruments = safe_cast<CCalibrationHelperVector^>(_NCIinstruments);
        std::vector<boost::shared_ptr<QuantLib::CalibrationHelper> >& _instruments = static_cast<std::vector<boost::shared_ptr<QuantLib::CalibrationHelper> >&> (_NCinstruments->GetShared ());
    	QuantLib::Real _rv = (QuantLib::Real)(*_ppCalibratedModel)->value ( _p_params,  _instruments );   
        Double _nrv = (Double)ValueHelper::Convert (_rv); //c
    	return _nrv;
	}
    catch (QuantLib::Error& _error)
    {
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown quantlib error"));
        
    }
	catch (std::exception& _error)
	{
        if (_error.what())
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String(_error.what()));
        else
		    throw REFNEW NativeExcpetion (REFNEW PLATFORM::String("Unknown std::exception"));
	}
    finally
    {
        if (_Cp_params != nullptr) _Cp_params->Unlock();
        if (instruments != nullptr) instruments->Unlock(); //NO2  
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory class

Cephei::QL::Models::ICalibratedModel^ Cephei::QL::Models::CCalibratedModel_Factory::Create (UInt64 nArguments)
{
    return REFNEW CCalibratedModel ( nArguments);
}
